<script lang="ts" setup>
import { getCurrentInstance, reactive, ref } from 'vue'
import { onLoad, onPageScroll, onReady } from '@dcloudio/uni-app'
import TnPopup from '@tuniao/tnui-vue3-uniapp/components/popup/src/popup.vue'
import TnTitle from '@tuniao/tnui-vue3-uniapp/components/title/src/title.vue'
import TnRadio from '@tuniao/tnui-vue3-uniapp/components/radio/src/radio.vue'
import TnInput from '@tuniao/tnui-vue3-uniapp/components/input/src/input.vue'
import TnRadioGroup from '@tuniao/tnui-vue3-uniapp/components/radio/src/radio-group.vue'
import TnListItem from '@tuniao/tnui-vue3-uniapp/components/list/src/list-item.vue'
import { tnNavPage } from '@tuniao/tnui-vue3-uniapp/utils'
import type { NavbarRectInfo } from '@tuniao/tnui-vue3-uniapp/components/navbar'
import PageContainer from '@/components/page-container/index.vue'
import { useScrollTransparentNavbar } from '@/hooks'
import {
  CHANNEL,
  FILE_URL,
  MP_API_URL,
  SYSTEM_CONFIG,
  USER_TOKEN,
} from '@/api/config'
import circles from '@/api/circles.js'

// 导航栏的高度
const navbarHeight = ref(0)
const instance = getCurrentInstance()

const { init: initTransparentScroll, opacityScrollHandle } =
  useScrollTransparentNavbar(instance)

// 导航栏初始化完毕
const navbarInitFinishHandle = (info: NavbarRectInfo) => {
  navbarHeight.value = info.height
}
const state = reactive({
  loading: false,
  circlesId: 0,
  joinMethodPopup: false,
  introducePopup: false,
  wechatIdPopup: false,
  circlesNamePopup: false,
  systemConfig: {
    circles: {
      circles_name_year_alter_num: '',
      vip_circles_name_year_alter_num: '',
    },
  },
  circlesInfo: {
    id: 0,
    name: '',
    user_id: '',
    user_ids: '',
    image: '',
    bg_image: '',
    circles_type_id: 0,
    poiaddress: '',
    longitude: '',
    latitude: '',
    introduce: '',
    open_plate: '',
    status: '',
    ban_date: '',
    wechat_id: '',
    join_method: 10,
  },
  channel: '',
})

const saveCirclesInfo = (data: object) => {
  state.loading = true
  circles
    .updateCirclesInfo(data, state.circlesInfo.id)
    .then((res) => {
      uni.showToast({
        title: res.msg,
        icon: 'none',
      })
      if (res.code == 1) {
        state.loading = false
      }
    })
    .catch((err) => {
      console.log(err)
    })
}

const joinMethod = () => {
  state.joinMethodPopup = true
}
const confirmJoinMethod = () => {
  saveCirclesInfo({
    join_method: state.circlesInfo.join_method,
  })
  state.joinMethodPopup = false
}

const introduce = () => {
  state.introducePopup = true
}
const confirmIntroduce = () => {
  saveCirclesInfo({
    introduce: state.circlesInfo.introduce,
    channel: state.channel,
  })
  state.introducePopup = false
}

const wechatid = () => {
  state.wechatIdPopup = true
}
const confirmWechatId = () => {
  saveCirclesInfo({
    wechat_id: state.circlesInfo.wechat_id,
    channel: state.channel,
  })
  state.wechatIdPopup = false
}

const circlesName = () => {
  state.circlesNamePopup = true
}
const confirmCirclesName = () => {
  saveCirclesInfo({
    name: state.circlesInfo.name,
    channel: state.channel,
  })
  state.circlesNamePopup = false
}
const chooseCirclesImageFile = () => {
  uni.chooseImage({
    count: 1,
    success(res) {
      if (res.errMsg == 'chooseImage:ok') {
        const tempFilePaths = res.tempFilePaths
        uni.uploadFile({
          url: `${MP_API_URL}/system.System/upload`,
          filePath: tempFilePaths[0],
          name: 'file',
          header: {
            Authorization: uni.getStorageSync(USER_TOKEN),
          },
          formData: {
            typeEnum: 'IMAGE',
          },
          success(uploadFileRes) {
            const result = JSON.parse(uploadFileRes.data)
            if (result.code == 1) {
              state.circlesInfo.image = result.data.file.url
              saveCirclesInfo({
                image: result.data.file.url,
                channel: state.channel,
              })
            }
          },
          fail(uploadFileErr) {
            console.log(uploadFileErr)
            uni.showToast({
              title: uploadFileErr,
              icon: 'none',
            })
          },
        })
      }
    },
  })
}
const chooseCirclesBgImageFile = () => {
  uni.chooseImage({
    count: 1,
    success(res) {
      if (res.errMsg == 'chooseImage:ok') {
        const tempFilePaths = res.tempFilePaths
        uni.uploadFile({
          url: `${MP_API_URL}/system.System/upload`,
          filePath: tempFilePaths[0],
          name: 'file',
          header: {
            Authorization: uni.getStorageSync(USER_TOKEN),
          },
          formData: {
            typeEnum: 'IMAGE',
          },
          success(uploadFileRes) {
            const result = JSON.parse(uploadFileRes.data)
            if (result.code == 1) {
              state.circlesInfo.bg_image = result.data.file.url
              saveCirclesInfo({
                bg_image: result.data.file.url,
                channel: state.channel,
              })
            }
          },
          fail(uploadFileErr) {
            console.log(uploadFileErr)
            uni.showToast({
              title: uploadFileErr,
              icon: 'none',
            })
          },
        })
      }
    },
  })
}

const getArticleDetail = () => {
  circles
    .circlesDetail({
      circles_id: state.circlesId,
    })
    .then((res) => {
      if (res.code == 1) {
        state.circlesInfo = res.data
      }
    })
    .catch((err) => {
      console.log(err)
    })
}
const navManageMember = () => {
  tnNavPage(
    `/circlesPages/manage/member?circlesId=${state.circlesId}&circleMasterUserId=${state.circlesInfo.id}`
  )
}
const navManageApplying = () => {
  tnNavPage(`/circlesPages/manage/applying?circlesId=${state.circlesId}`)
}
const navManageBlacklist = () => {
  tnNavPage(`/circlesPages/manage/blacklist?circlesId=${state.circlesId}`)
}
const navTopup = () => {
  tnNavPage(`/circlesPages/manage/topup?circlesId=${state.circlesId}`)
}
const navCirclesZone = (plate: string, status: string) => {
  tnNavPage(
    `/circlesPages/manage/zone?circlesId=${state.circlesId}&plate=${plate}&switch=${status}`
  )
}
const isPlateInString = (plate: string) => {
  const arrayFromString = state.circlesInfo.open_plate.split(',')
  const trimmedArray = arrayFromString.map((item) => item.trim())
  return trimmedArray.includes(plate)
}
onLoad((options) => {
  if (!options?.circlesId) {
    uni.showModal({
      title: '提示',
      content: '参数错误',
      showCancel: false,
      success: () => {
        uni.navigateBack()
      },
    })
    return
  }
  state.circlesId = options.circlesId
  getArticleDetail()

  state.systemConfig = uni.getStorageSync(SYSTEM_CONFIG)
  state.channel = uni.getStorageSync(CHANNEL)
})
onReady(() => {
  initTransparentScroll()
})
onPageScroll((e) => {
  opacityScrollHandle(e.scrollTop)
})
</script>

<template>
  <PageContainer :placeholder-bottom="true">
    <TnNavbar
      fixed
      :bottom-shadow="false"
      :placeholder="false"
      @init-finish="navbarInitFinishHandle"
    >
      圈子管理
    </TnNavbar>
    <view class="container">
      <!-- 方式1 start-->
      <view
        class="tn-margin-top-sm"
        :style="{ paddingTop: `${navbarHeight + 10}px` }"
      >
        <view class="">
          <view class="list-container">
            <TnTitle
              mode="hLine"
              title="基本信息"
              color="tn-type-primary"
              size="30rpx"
              class="title"
            />
            <view class="list-item">
              <TnListItem
                bottom-border
                bottom-border-indent
                right-icon="right"
                :custom-style="{
                  borderRadius: '15rpx 15rpx 0rpx 0rpx',
                }"
              >
                <view class="list-content" @tap.stop="circlesName">
                  <view class="text tn-flex">圈子名称</view>
                  <view class="tn-text-xs sub-text">
                    每年修改
                    {{ state.systemConfig.circles.circles_name_year_alter_num }}
                    次，会员
                    {{ state.systemConfig.circles.vip_circles_name_year_alter_num }}
                    次
                  </view>
                </view>
              </TnListItem>
              <TnListItem bottom-border bottom-border-indent right-icon="right">
                <view class="list-content" @tap.stop="wechatid">
                  <view class="text">圈主微信</view>
                  <view class="tn-text-xs sub-text">
                    {{ state.circlesInfo.wechat_id }}
                  </view>
                </view>
              </TnListItem>
              <TnListItem bottom-border bottom-border-indent right-icon="right">
                <view class="list-content" @tap.stop="introduce">
                  <view class="text tn-flex">圈子介绍</view>
                  <view class="tn-text-xs sub-text"> 查看 </view>
                </view>
              </TnListItem>
              <TnListItem bottom-border bottom-border-indent right-icon="right">
                <view class="list-content">
                  <view>
                    <view class="title">圈子logo</view>
                    <view class="sub-title tn-text-xs">
                      每年修改
                      {{ state.systemConfig.circles.circles_logo_year_alter_num }}
                      次，会员
                      {{ state.systemConfig.circles.vip_circles_logo_year_alter_num }}
                      次
                    </view>
                  </view>
                  <view class="tn-text-xs sub-text">
                    <image
                      :src="FILE_URL + state.circlesInfo.image"
                      mode="aspectFit"
                      style="width: 70rpx; height: 70rpx"
                      @click="chooseCirclesImageFile"
                    />
                  </view>
                </view>
              </TnListItem>
              <TnListItem
                right-icon="right"
                :custom-style="{
                  borderRadius: '0rpx 0rpx 15rpx 15rpx',
                }"
              >
                <view class="list-content">
                  <view>
                    <view class="title">圈子背景图</view>
                    <view class="sub-title tn-text-xs">
                      每年修改
                      {{ state.systemConfig.circles.circles_bg_year_alter_num }}
                      次，会员
                      {{ state.systemConfig.circles.vip_circles_bg_year_alter_num }}
                      次
                    </view>
                  </view>
                  <view class="tn-text-xs sub-text">
                    <image
                      :src="FILE_URL + state.circlesInfo.bg_image"
                      mode="aspectFit"
                      style="width: 130rpx; height: 70rpx"
                      @click="chooseCirclesBgImageFile"
                    />
                  </view>
                </view>
              </TnListItem>
            </view>
          </view>

          <view class="list-container">
            <TnTitle
              mode="hLine"
              title="成员管理"
              color="tn-type-primary"
              size="30rpx"
              class="title"
            />
            <view class="list-item">
              <TnListItem
                bottom-border
                bottom-border-indent
                right-icon="right"
                :custom-style="{
                  borderRadius: '15rpx 15rpx 0rpx 0rpx',
                }"
              >
                <view class="list-content" @tap.stop="joinMethod">
                  <view class="text tn-flex">成员加入方式</view>
                  <view class="tn-text-xs sub-text">
                    <text v-if="state.circlesInfo.join_method == 10">
                      直接加入
                    </text>
                    <text v-else-if="state.circlesInfo.join_method == 20">
                      需申请
                    </text>
                    <text v-else>需申请（填写理由）</text>
                  </view>
                </view>
              </TnListItem>
              <TnListItem bottom-border bottom-border-indent right-icon="right">
                <view class="list-content" @tap.stop="navManageMember">
                  <view class="text">成员列表</view>
                  <view class="tn-text-xs sub-text"> 查看 </view>
                </view>
              </TnListItem>
              <TnListItem bottom-border bottom-border-indent right-icon="right">
                <view class="list-content" @tap.stop="navManageApplying">
                  <view class="text">成员申请</view>
                  <view class="tn-text-xs sub-text"> 查看 </view>
                </view>
              </TnListItem>
              <TnListItem
                right-icon="right"
                :custom-style="{
                  borderRadius: '0rpx 0rpx 15rpx 15rpx',
                }"
              >
                <view class="list-content" @tap.stop="navManageBlacklist">
                  <view class="text">黑名单</view>
                  <view class="tn-text-xs sub-text">
                    禁止加入本圈或评论动态
                  </view>
                </view>
              </TnListItem>
            </view>
          </view>

          <view class="list-container">
            <TnTitle
              mode="hLine"
              title="内容管理"
              color="tn-type-primary"
              size="30rpx"
              class="title"
            />
            <view class="list-item">
              <TnListItem
                bottom-border
                bottom-border-indent
                right-icon="right"
                :custom-style="{
                  borderRadius: '15rpx',
                }"
              >
                <view class="list-content" @tap.stop="navTopup">
                  <view class="text tn-flex">置顶管理</view>
                  <view class="tn-text-xs sub-text"> 查看 </view>
                </view>
              </TnListItem>
            </view>
          </view>

          <view class="list-container">
            <TnTitle
              mode="hLine"
              title="板块管理"
              color="tn-type-primary"
              size="30rpx"
              class="title"
            />
            <view class="list-item">
              <TnListItem
                bottom-border
                bottom-border-indent
                right-icon="right"
                :custom-style="{
                  borderRadius: '15rpx 15rpx 0rpx 0rpx',
                }"
              >
                <view class="list-content">
                  <view class="text tn-flex">动态</view>
                  <view
                    v-if="isPlateInString('dynamic')"
                    class="tn-text-xs sub-text"
                    @tap.stop="navCirclesZone('dynamic', 'open')"
                  >
                    开启
                  </view>
                  <view
                    v-else
                    class="tn-text-xs sub-text"
                    @tap.stop="navCirclesZone('dynamic', 'close')"
                  >
                    已关闭
                  </view>
                </view>
              </TnListItem>
              <TnListItem bottom-border bottom-border-indent right-icon="right">
                <view class="list-content">
                  <view class="text">闲置</view>
                  <view
                    v-if="isPlateInString('usedIdle')"
                    class="tn-text-xs sub-text"
                    @tap.stop="navCirclesZone('usedIdle', 'open')"
                  >
                    开启
                  </view>
                  <view
                    v-else
                    class="tn-text-xs sub-text"
                    @tap.stop="navCirclesZone('usedIdle', 'close')"
                  >
                    已关闭
                  </view>
                </view>
              </TnListItem>
              <TnListItem
                right-icon="right"
                :custom-style="{
                  borderRadius: '0rpx 0rpx 15rpx 15rpx',
                }"
              >
                <view class="list-content">
                  <view class="text">组局</view>
                  <view
                    v-if="isPlateInString('organizeBureau')"
                    class="tn-text-xs sub-text"
                    @tap.stop="navCirclesZone('organizeBureau', 'open')"
                  >
                    开启
                  </view>
                  <view
                    v-else
                    class="tn-text-xs sub-text"
                    @tap.stop="navCirclesZone('organizeBureau', 'close')"
                  >
                    已关闭
                  </view>
                </view>
              </TnListItem>
            </view>
          </view>
        </view>
      </view>

      <view class="tn-tabbar-height" />
    </view>
  </PageContainer>

  <!-- 成员加入方式 -->
  <TnPopup
    v-model="state.joinMethodPopup"
    :overlay-closeable="false"
    :close-btn="true"
    width="80%"
    height="360"
  >
    <view class="tn-p tn-text-center tn-text-lg"> 成员加入方式 </view>
    <view class="tn-pl tn-pr">
      <TnRadioGroup v-model="state.circlesInfo.join_method" border>
        <TnRadio :label="10">直接加入</TnRadio>
        <TnRadio :label="20">需申请</TnRadio>
        <TnRadio :label="30">需申请(填写理由)</TnRadio>
      </TnRadioGroup>
    </view>
    <view class="tn-pt">
      <TnButton text width="100%" size="lg" @click="confirmJoinMethod">
        确认
      </TnButton>
    </view>
  </TnPopup>

  <!-- 圈子名称 -->
  <TnPopup
    v-model="state.circlesNamePopup"
    :overlay-closeable="false"
    :close-btn="true"
    width="80%"
    height="280"
  >
    <view class="tn-p tn-text-center tn-text-lg"> 修改圈子名称 </view>
    <view class="tn-pl tn-pr">
      <TnInput
        v-model="state.circlesInfo.name"
        :underline="true"
        :maxlength="20"
        placeholder="请填写圈子名称"
      />
    </view>
    <view class="tn-pt">
      <TnButton text width="100%" size="lg" @click="confirmCirclesName">
        确认
      </TnButton>
    </view>
  </TnPopup>

  <!-- 圈主微信 -->
  <TnPopup
    v-model="state.wechatIdPopup"
    :overlay-closeable="false"
    :close-btn="true"
    width="80%"
    height="280"
  >
    <view class="tn-p tn-text-center tn-text-lg"> 更新圈主微信 </view>
    <view class="tn-pl tn-pr">
      <TnInput
        v-model="state.circlesInfo.wechat_id"
        :underline="true"
        :maxlength="30"
        placeholder="请填写圈主微信"
      />
    </view>
    <view class="tn-pt">
      <TnButton text width="100%" size="lg" @click="confirmWechatId">
        确认
      </TnButton>
    </view>
  </TnPopup>

  <!-- 圈子介绍 -->
  <TnPopup
    v-model="state.introducePopup"
    :overlay-closeable="false"
    :close-btn="true"
    width="80%"
    height="400"
  >
    <view class="tn-p tn-text-center tn-text-lg"> 更新圈子介绍 </view>
    <view class="tn-pl tn-pr">
      <TnInput
        v-model="state.circlesInfo.introduce"
        type="textarea"
        :underline="true"
        :maxlength="255"
        height="190"
        placeholder="请填写圈子介绍"
      />
    </view>
    <view class="tn-pt">
      <TnButton text width="100%" size="lg" @click="confirmIntroduce">
        确认
      </TnButton>
    </view>
  </TnPopup>
</template>

<style lang="scss" scoped>
@use '../styles/manage/manage.scss';
</style>
